import React, { PropsWithChildren, Fragment, useRef, useEffect } from "react";
import { connect } from "react-redux";
import { RouteComponentProps } from "react-router-dom";
import actions from "src/store/actions/home";
import HomeHeader from "src/components/HomeHeader";
import { CombinedState } from "src/store/reducers";
import { HomeState } from "src/store/reducers/home";
import HomeSliders from "src/components/HomeSliders";

import LessonList from "src/components/LessonList";
import { loadMore, downRefresh, store, debounce, throttle } from "src/utils";

import "./index.less";

let mapStateToProps = (state: CombinedState): HomeState => state.home;

interface Params { }

type stateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof actions; //action的类型

type HomeProps = PropsWithChildren<
  RouteComponentProps<Params> & stateProps & DispatchProps
>;

function HomePage(props: HomeProps) {
  console.log(props);
  const homeContainerRef = useRef(null);
  const lessonListRef = useRef(null);

  useEffect(() => {
    loadMore(homeContainerRef.current, props.getLessons);
    downRefresh(homeContainerRef.current, props.refreshLessons);
    homeContainerRef.current.addEventListener("scroll", () =>
      lessonListRef.current()
    );
    if (props.lessons) {
      homeContainerRef.current.scrollTop = store.get("homeScrollTop");
    }
    return () => {
      store.set("homeScrollTop", homeContainerRef.current.scrollTop);
    };
  }, []);

  return (
    <Fragment>
      <HomeHeader
        currentCategory={props.currentCategory}
        setCurrentCategory={props.setCurrentCategory}
      />
      <div className="home-container" ref={homeContainerRef}>
        <HomeSliders sliders={props.sliders} getSliders={props.getSliders} />
        <LessonList
          ref={lessonListRef}
          container={homeContainerRef}
          lessons={props.lessons}
          getLessons={props.getLessons}
        />
      </div>
    </Fragment>
  );
}

export default connect(mapStateToProps, actions)(HomePage);
